/**
 * 526. 优美的排列
 * https://leetcode.cn/problems/beautiful-arrangement/description/
 */
class Solution4 {
    int n;
    int ret;
    boolean[] check;
    public int countArrangement(int _n) {
        n = _n; ret = 0;
        check = new boolean[n + 1];
        dfs(1);
        return ret;
    }

    public void dfs(int pos) {
        if(pos > n) {
            ret++;
            return;
        }

        for(int i = 1; i <= n; i++) {
            if(!check[i] && (judge(i, pos) || judge(pos, i))) {
                check[i] = true;
                dfs(pos + 1);
                check[i] = false;
            }
        }
    }

    public boolean judge(int prem, int i) {
        if(prem % i == 0 || i % prem == 0) return true;
        else return false;
    }
}